<?php

namespace addons\kuerp\controller;

use addons\kuerp\model\Contacts as ContactsModel;
use addons\kuerp\model\ContactsFile;
use addons\kuerp\model\CustomersUser;
use addons\kuerp\model\ContactsOther;
use addons\kuerp\model\Form;
use addons\kuerp\model\FormField;
use addons\kuerp\model\Mobilecode;
use addons\kuerp\model\Person;
use addons\kuerp\model\OperationLog;
use addons\kuerp\model\Staff;
use app\admin\model\department\Admin;
use app\admin\model\kuerp\StaffMember;
use think\Db;
use think\Exception;
/**
 * 联系人接口
 */
class Contacts extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];


	//创建联系人
	public function addContacts() {
		$params = $this->request->post();
		if (empty($params['contacts'])) {
			$this->error('联系人信息不能为空');
		}
		// 表单验证
		// if (($result = $this->kuerpValidate($params['contacts'],get_class(), 'create')) !== true) {
		// 	$this->error($result);
		// }
        $mobile =$params['contacts']['first_connect_mobile']??'';
        $email =$params['contacts']['qq_wx_email']??'';
        if($mobile){
            if (ContactsModel::where([
                'sid'=>$params['contacts']['customer_id'],
                'first_connect_mobile' => $mobile,
            ])->find()) {
                $this->error('联系人手机号已存在');
            }
        }

        $result = FormField::checkFields(FormField::CONTACTS_TYPE,$params['contacts']);
        if ($result !== true) {
            $this->error($result);
        }

		Db::startTrans();
		try {
            
			// if(empty($mobile) && empty($email)){
			// 	$this->error('手机号码和邮箱至少填写一项！');
			// }
			$rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';
			$rule2 = '^\d+$^';
			if (preg_match($rule2, $mobile) ==false) {
				$this->error('手机号格式错误');
			}
			ContactsModel::createContacts($params['contacts']);
			// $personModel = new Person();
            // if($personId = $personModel->where(['account'=>$mobile])->value('id')){
            //     $personModel->where('id',$personId)->update(['customer_id'=>$params['contacts']['customer_id']]);
            // }
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		if ($result) {
			$this->success('创建联系人成功');
		}
	}


	//编辑联系人
	public function editContacts() {
		$id     = input('id');
		$params = $this->request->post();
		$row    = ContactsModel::where(['id' => $id])->find();
		if (empty($row)) {
			$this->error('客户信息不存在');
		}
		// 表单验证
		// if (($result = $this->kuerpValidate($params,get_class(), 'edit')) !== true) {
		// 	$this->error($result);
		// }
		if (ContactsModel::where([
			'first_connect_mobile' => $params['first_connect_mobile'],
			'sid'         => $row['sid'],
			'id'          => ['neq', $params['id']]
		])->find()) {
			$this->error('联系人手机号已存在');
		}

        $result = FormField::checkFields(FormField::CONTACTS_TYPE,$params,$id);
        if ($result !== true) {
            dump($result);
            $this->error($result);
        }
		Db::startTrans();
		try {
			ContactsModel::updateContacts($params, $row);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}

		$this->success('编辑联系人成功');
	}

    //姓名是否重复
    public function isNameDuplicate(){
        $name=input('name');
       $contacts= ContactsModel::where(['first_connect_name'=>$name])->with('customer')->find();
       if(!empty($contacts)){
           $this->error('联系人名称已存在于客户【'.$contacts['customer']['name'].'】名下');
       }
       $this->success('不重复');
    }

	//删除联系人
	public function delContacts() {
		//判断是否有权限
		if ($this->auth->check('kuerp/customers/deluser,kuerp/customers_user/del') === false) {
			$this->error('权限不足，无法删除当前联系人');
		}
		$id = input('id');
		$row = ContactsModel::where(['id' => $id])->find();
		if (empty($row)) {
			$this->error('您不是客户归属人，无法删除当前联系人');
		}
		$model = new ContactsModel();
		if ($model->destroy(['id' => $id])) {
			$this->success('删除成功');
		}
		OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $row['sid'], '删除联系人:' . $row['first_connect_name']);
		$this->error('删除失败');
	}


	//获取联系人列表
	public function getList() {
		$limit       = input("limit/d", 10);
		$customer_id = input('customer_id');
		$name        = input('name');
        $params = $this->request->post();

        $where= [];//FormField::updateWhereField(FormField::CONTACTS_TYPE,$params);
		if ($customer_id) {
			$where['sid'] = $customer_id;
		}
		if ($name) {
			$where['first_connect_name|first_connect_mobile|customers.customer_name'] = ['like', "%{$name}%"];
		}
        if (isset($params['createtime']) && $params['createtime']) {//创建时间
            $createtime = $params['createtime'];
            $times = setTimes($createtime, 'time');
            $where['createtime'] = ['between', $times];
        }
//        $ruleWhere = [];
//        if($this->auth->id !== 1){
//            if ($this->auth->is_sale) {
//                $ruleWhere['staff_member_id'] = ['exp', Db::raw(' in (0, '.$this->auth->staff_member_id.')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
//            }
//            //部门经理查看部门成员 上级部门能查看下级部门
//            $adminids = (new Admin())->getChildrenAdminIds($this->auth->id, true);
//            $sale_users = [];
//            //转为职员id
//            if ($adminids) {
//                $sale_users = (new StaffMember())->getStaffMemberIds($adminids);
//            }
//            if ($sale_users) {
//                // $ruleWhere = ['staff_member_id' => ['in', $sale_users]];
//                $ruleWhere['staff_member_id'] = ['exp', Db::raw(' in ('.implode(',', $sale_users).')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
//            } else {
//                $ruleWhere['staff_member_id'] = ['exp', Db::raw(' =-1  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
//            }
//        }



        //0全部 1 我负责  2 下属负责的
       if (isset($params['staff_id']) && $params['staff_id']) {//下级员工筛选
           $where['staff_member_id'] = $params['staff_id'];
       } else {
           $type = $params['type'] ?? 0;
           if ($type == 1) {//我负责的
               $where['staff_member_id'] = ['exp', Db::raw(' = '.$this->auth->staff_member_id.'  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];//$this->auth->staff_member_id;
           } elseif ($type == 2) {//下属负责的
            //    $where['staff_member_id'] = ['in', Staff::getLowerStaffId()];
			   $sale_users = $this->auth->sale_users;
				//本人存在 则剔除自己
				if (in_array($this->auth->staff_member_id,$sale_users)) {
					$sale_users = array_diff($sale_users, [$this->auth->staff_member_id]);
				}
				$where['staff_member_id'] = ['exp', Db::raw(' in ('.implode(',', $sale_users).')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];//['in', $sale_users];
           }else{
            //    $where['staff_member_id'] = ['in', Staff::getMyStaffIds()];
			   $where['staff_member_id'] = ['exp', Db::raw(' in ('.implode(',', $this->auth->sale_users).')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
           }
       }
		$records                 = ContactsModel::where($where)->with(['customers'])->order('id desc')->paginate($limit);
		foreach ($records as $row) {
            $row->getRelation('customers')->visible(['customer_name']);
        }
    
        $this->success('请求成功', $records);
	}


	//获取select联系人列表
	public function getSelectList() {
		$customer_id = input('customer_id');
		$name = input('name');
		$where       = [];
		if ($customer_id) {
			$where['sid'] = $customer_id;
		}
		if ($name) {
			$where['first_connect_name'] = ['like',"%{$name}%"];
		}
		$list = ContactsModel::where($where)->field('id,first_connect_name as name,first_connect_mobile as mobile')->order('is_first desc,id desc')->select();
		$list = collection($list)->toArray();
		foreach ($list as $k => $v) {
			$v['new_mobile'] = $v['mobile'];
			$list[$k]        = $v;
		}
		$this->success('请求成功', $list);
	}


	//获取联系人详情
	public function getDetail() {
		$id       = input('id');
        $ContactsModel=new ContactsModel();
		$contract = $ContactsModel->get(['id' => $id],[
            'customer',
//            'ownerStaff'
        ]);
		if (empty($contract)) {
			$this->error('信息不存在');
		}
        $mobile= $contract->getData('first_connect_mobile');
		$contract               = $contract->toArray();
        $contract['mobile']=$mobile;
        $contract['name']= $contract['first_connect_name'];
        $contract['customer_name']= $contract['customer']['customer_name'];
		$this->success('请求成功', $contract);
	}


	//获取附件列表
	public function getFilesList() {
		$id = input('contacts_id');

		$files = ContactsFile::where(['contacts_id' => $id])->field('file_id')->with(['file'])->select();
		$this->success('请求成功', $files);
	}

	//获取国外电话区号
    public function getMobileCode() {
        $name       = input('name');
        $where =[];
        if(isset($name) && !empty($name)){
            $where['name|number'] = ['like','%'.$name.'%'];
        }
        $list = Mobilecode::where($where)->orderRaw('CONVERT(name using gbk) asc')->select();
        $this->success('',$list);

    }

    // 获取邮箱列表
    public function getEmails() {
        $name = input('name','');
        $where['email'] = [['not null',''],['neq',''],'and'];
        if(isset($name) && $name){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $list = \addons\kuerp\model\Contacts::where($where)->field('id,name,email')->select();
        $this->success('',$list);
    }

}
